package com.feihong.yw189.paidan.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;

import com.blankj.utilcode.util.AppUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.bluetooth.utils.util.PrefUtils;
import com.feihong.yw189.fragment.base.BaseFragment;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.paidan.activity.DispatchActivity;
import com.feihong.yw189.paidan.qiangdanservice.LocationCallBack;
import com.feihong.yw189.paidan.qiangdanservice.LocationInfo;
import com.feihong.yw189.paidan.qiangdanservice.LocationToolsOnces;
import com.feihong.yw189.paidan.qiangdanservice.newversion.PaiDanRemoteService;
import com.feihong.yw189.paidan.view.X5WebView;
import com.feihong.yw189.utils.UserLoginInfo;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;


/**
 * Created by admin on 2018/2/28.
 */

public class DispatchWebLocation extends BaseFragment {

    private static final String TAG = "派单";
    private DispatchActivity mActivity;
    private X5WebView webView;
    LocationToolsOnces locationToolsOnces;
    private boolean fristLoad = true;
    private String url;


    public static DispatchWebLocation newInstance(String tabName) {
        DispatchWebLocation rechargeFragment = new DispatchWebLocation();
        return rechargeFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = (DispatchActivity) getActivity();
        locationToolsOnces = new LocationToolsOnces(getContext(), callBack);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.framgent_webqiangdan, container, false);
        return fragmentView;
    }

    @Override
    protected void setTheme() {
        isDrakFont = false;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
    }

    private LocationCallBack callBack = new LocationCallBack() {
        @Override
        public void successGetLocation(LocationInfo info) {

            webView.loadUrl("javascript:getOrderData()");
        }

        @Override
        public void error(String error) {
            switch (error) {
                case "4":
                case "5":
                    showSystemToast("定位失败,请检查网络");
                    break;
                case "12":
                    showSystemToast("请开启app的定位权限");
                    break;
                case "13":
                    showSystemToast("定位失败,请检查网络以及定位权限是否授予");
                    break;
                case "14":
                    showSystemToast("定位失败,请到相对开阔的露天场所再次尝试");
                    break;
                case "18":
                    showSystemToast("定位失败,建议手机关闭飞行模式，并打开WIFI开关");
                    break;
                case "19":
                    showSystemToast("定位失败,建议手机插上sim卡，并打开WIFI开关");
                    break;
                default:
                    showSystemToast("定位失败,请退出当前界面重试");
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        if (webView != null) {
            try {
                //   webView.pauseTimers();
                webView.stopLoading();
                webView.removeAllViews();
                webView.destroy();
            } catch (Exception ex) {

            }
        }
        super.onDestroy();
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (webView != null) {
            webView.stopLoading();
        }
        if (isInit) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    bindData();
                    fristLoad = false;
                }
            }, 300);
        }
    }

    public String getToken() {
        String token = UserLoginInfo.getUserLoginInfoInstance().getUserToken();
        String version = AppUtils.getAppVersionName();
        return "token=" + token + "&version=" + version + "&t=" + System.currentTimeMillis();
    }


    /**
     * 初始化布局
     */
    @Override
    public void initView() {
        webView = (X5WebView) findView(R.id.webviewframe);
        url = HttpTools.PAIDAN_DITU + "?" + getToken();
        initWebViewSettings();

    }

    @Override
    public void bindData() {
        LocationManager lm = (LocationManager) _mActivity.getSystemService(Context.LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (ok) {
            webView.loadUrl(url);
        } else {
            new AlertDialog.Builder(_mActivity)
                    .setPositiveButton("去打开", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(@NonNull DialogInterface dialog, int which) {
                            Intent intenta = new Intent();
                            intenta.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intenta, 1315);
                        }
                    })
                    .setCancelable(false)
                    .setMessage("位置服务开关未打开")
                    .show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK && requestCode == 1315){
            bindData();
        }
    }

    class myWebClinet extends WebViewClient {
        @Override
        public void onPageFinished(WebView webView, String s) {
            super.onPageFinished(webView, s);
            findView(R.id.loading).setVisibility(View.GONE);
            String lasttime = PrefUtils.getString(getContext(), PaiDanRemoteService.LAST_LOC_TIME, "0");
            if (TextUtils.isEmpty(lasttime)) {
                locationToolsOnces.startLocation(0);
            } else {
                long l = Long.parseLong(lasttime);
                long curr = System.currentTimeMillis();
                curr = (curr - l) / 1000;
                if (curr > 30) {//30秒内不需要重新定位
                    locationToolsOnces.startLocation(0);
                } else {
                    webView.loadUrl("javascript:getOrderData()");
                }
            }
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String s) {
            return super.shouldOverrideUrlLoading(webView, s);
        }

        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {
            super.onReceivedError(webView, i, s, s1);
            // ToastUtils.showShortToast(getContext(), "页面加载失败！");
        }

        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);
        }
    }


    private void initWebViewSettings() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setAllowFileAccess(true);
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportMultipleWindows(false);
        settings.setAppCacheEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setAppCacheMaxSize(Long.MAX_VALUE);
        settings.setPluginState(WebSettings.PluginState.ON_DEMAND);

        webView.setWebViewClient(new myWebClinet());
        webView.setWebChromeClient(new WebChromeClient());
        webView.addJavascriptInterface(new AndroidtoJs(), "webInterface");
    }


    // 继承自Object类
    public class AndroidtoJs extends Object {

        // 定义JS需要调用的方法
        // 被JS调用的方法必须加入@JavascriptInterface注解
        @JavascriptInterface
        public String getParams() {
            String token = UserLoginInfo.getUserLoginInfoInstance().getUserToken();
            String version = AppUtils.getAppVersionName();
            String Longitude = PrefUtils.getString(getContext(), PaiDanRemoteService.PaiDanLongitude, "");
            String Latitude = PrefUtils.getString(getContext(), PaiDanRemoteService.PaiDanLatitude, "");
            return "token=" + token + "&version=" + version + "&Latitude=" + Latitude + "&Longitude=" + Longitude + "";
        }

        @JavascriptInterface
        public String getToken() {
            String token = UserLoginInfo.getUserLoginInfoInstance().getUserToken();
            String version = AppUtils.getAppVersionName();
            return "token=" + token + "&version=" + version;
        }

        @JavascriptInterface
        public String getLocation() {
            String Longitude = PrefUtils.getString(getContext(), PaiDanRemoteService.PaiDanLongitude, "");
            String Latitude = PrefUtils.getString(getContext(), PaiDanRemoteService.PaiDanLatitude, "");
            return Longitude + "|" + Latitude;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (webView != null) {
            webView.onResume();
        }
        fristLoad = false;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
        }
        fristLoad = true;
    }

}